﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using Microsoft.DeepZoomTools;
using SmartMosaicServer;
using System.Data.SqlClient;
using SmartMosaic.Upload;

namespace SSM.SmartMosaicServer
{
    /// <summary>
    /// Summary description for SmartMosaicServerWebservice
    /// </summary>
    [WebService(Namespace = "http://www.secmem.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class SmartMosaicServerWebservice : System.Web.Services.WebService
    {
        private string INPUT_DIRECTORY =
            "C:\\SmartMosaicServer\\input";
        //"C:\\input";
        private string OUTPUT_DIRECTORY =
            "C:\\SmartMosaicServer\\output";
        private string DEEPZOOM_OUTPUT_DIRECTORY =
            "D:\\sourcecode\\codeplex\\SmartMosaic\\SmartMosaicServer\\UploadData";
        private string DEEPZOOM_URL =
            "http://211.189.20.163/SmartMosaicServer/UploadData/";
        private string DABASE_DIRECTORY =
            "D:\\photo\\auto\\theme\\";
        private string DABASE_URL =
            "http://211.189.20.163/SmartMosaicDataBase";

        [WebMethod]
        public string GetTileDetailedImage(int imageIndex, int horizontalIndex, int verticalIndex)
        {
            if (true)
                return "";

            string imageIndexFile = OUTPUT_DIRECTORY + "\\" + imageIndex + ".dat";

            StreamReader sr = File.OpenText(imageIndexFile);

            string dbUrl = "";
            string index = verticalIndex + "," + horizontalIndex;

            while (!sr.EndOfStream)
            {
                string result = sr.ReadLine();

                if (result.StartsWith(index))
                {
                    string[] str = result.Split(',');

                    dbUrl = str[2];

                    break;
                }
            }

            string imageUrl = dbUrl.Replace(DABASE_DIRECTORY, "");
            imageUrl = imageUrl.Replace("\\", "/");
            imageUrl = DABASE_URL + "/" + imageUrl;

            return imageUrl;
        }

        /// <summary>
        /// 최근의 Thumbnail을 가져옵니다.
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public string[] GetRecentMosaicThumbnails()
        {
            List<string> recentThumbnails = new List<string>();

            string url = "http://211.189.20.163/SmartMosaicServer/UploadData/7/dzc_output_files/8/0_0.jpg";
            string url2 = "http://211.189.20.163/SmartMosaicServer/UploadData/8/dzc_output_files/8/0_0.jpg";
            string url3 = "http://211.189.20.163/SmartMosaicServer/UploadData/10/dzc_output_files/8/0_0.jpg";
            string url4 = "http://211.189.20.163/SmartMosaicServer/UploadData/11/dzc_output_files/8/0_0.jpg";
            string url5 = "http://211.189.20.163/SmartMosaicServer/UploadData/12/dzc_output_files/8/0_0.jpg";
            string url6 = "http://211.189.20.163/SmartMosaicServer/UploadData/13/dzc_output_files/8/0_0.jpg";
            string url7 = "http://211.189.20.163/SmartMosaicServer/UploadData/14/dzc_output_files/8/0_0.jpg";

            recentThumbnails.Add(url);
            recentThumbnails.Add(url2);
            recentThumbnails.Add(url3);
            recentThumbnails.Add(url4);
            recentThumbnails.Add(url5);
            recentThumbnails.Add(url6);
            recentThumbnails.Add(url7);

            return recentThumbnails.ToArray<string>();
        }

        [WebMethod]
        public UploadResult UploadFile(byte[] file, string fileName, int themeCode)
        {
            string savedDir = "D:\\sourcecode\\codeplex\\SmartMosaic\\SmartMosaicServer\\UploadData\\index.txt";

            int USER_COUNT = 0;

            lock(GetType()) 
            {
                if (!File.Exists(savedDir))
                {
                    FileStream fs = File.Create(savedDir);

                    fs.Close();
                    fs.Dispose();
                }

                StreamReader sr = File.OpenText(savedDir);

                USER_COUNT = Convert.ToInt32(sr.ReadLine());
                USER_COUNT++;

                sr.Close();
                sr.Dispose();

                File.WriteAllText(savedDir, USER_COUNT.ToString());
            }

            // the byte array argument contains the content of the file
            // the string argument contains the name and extension
            // of the file passed in the byte array
            try
            {
                string newInputFileName = USER_COUNT + "" + themeCode + ".jpg";
                string newOutputFileName = USER_COUNT + ".jpg";
                string endOutputFileName = USER_COUNT + ".dat";

                // instance a memory stream and pass the
                // byte array to its constructor
                MemoryStream ms = new MemoryStream(file);

                // instance a filestream pointing to the 
                // storage folder, use the original file name
                // to name the resulting file
                FileStream fs = new FileStream
                    (INPUT_DIRECTORY + "\\" + newInputFileName, FileMode.Create);

                // write the memory stream containing the original
                // file as a byte array to the filestream
                ms.WriteTo(fs);

                // clean up
                ms.Close();
                fs.Close();
                fs.Dispose();

                // 여기서 파일 모니터하면 된다.
                while (!File.Exists(OUTPUT_DIRECTORY + "\\" + endOutputFileName))
                {
                    // 1초에 한번씩 체크
                    System.Threading.Thread.Sleep(1000);
                }
                
                // 파일이 생성된 경우
                // DeepZoomAPI 수행
                ImageCreator creator = new ImageCreator();
                creator.TileSize = 256;
                creator.TileFormat = Microsoft.DeepZoomTools.ImageFormat.Jpg;

                creator.CopyMetadata = false;
                creator.Create(OUTPUT_DIRECTORY + "\\" + newOutputFileName,
                    DEEPZOOM_OUTPUT_DIRECTORY + "\\" + USER_COUNT + "\\dzc_output.xml");

                UploadResult result = new UploadResult()
                {
                    UploadResultCode = UploadResultCodeEnum.Success,
                    Detail = (DEEPZOOM_URL + USER_COUNT)
                };

                // return OK if we made it this far
                return result;
            }
            catch (Exception ex)
            {
                // return the error message if the operation fails
                return new UploadResult()
                {
                    UploadResultCode = UploadResultCodeEnum.Fail,
                    Detail = ex.Message.ToString()
                }; ;
            }
        }
    }
}
